<template>
  <div class="app-container">
    <div class="app-container-flex">
      <div class="left-container">
        <div class="left-container-header border-style-bottom">
          <!-- 机构树 -->
          <div v-for="item in btnList.beforeList" :key="item.value">
            <el-button
              v-if="item.value === 'add'"
              :plain="true"
              :disabled="addBtn"
              @click="addOrg"
              >新增</el-button
            >
            <el-button
              v-if="item.value === 'delDept'"
              :plain="true"
              :disabled="!canDelete"
              @click="delDept"
              >删除</el-button
            >
            <el-button
              v-if="item.value === 'orgDeptImport'"
              :plain="true"
              @click="downloadTemplate('org_dept_import')"
              >下载部门模板</el-button
            >
            <el-upload
              v-if="item.value === 'orgDeptInput'"
              :headers="uploadInfo.headers"
              :show-file-list="false"
              :on-error="uploadError"
              :on-success="uploadSuccess"
              :before-upload="beforeUpload"
              :action="uploadInfo.action"
            >
              <el-button>导入部门</el-button>
            </el-upload>
            <el-button
              v-if="item.value === 'orgUserImport'"
              :plain="true"
              @click="downloadTemplate('org_user_import')"
              >下载人员模板</el-button
            >
            <el-upload
              v-if="item.value === 'orgUserInput'"
              :headers="uploadUserInfo.headers"
              :show-file-list="false"
              :on-error="uploadError"
              :on-success="uploadSuccess"
              :before-upload="beforeUpload"
              :action="uploadUserInfo.action"
            >
              <el-button>导入人员</el-button>
            </el-upload>
          </div>
          <el-dropdown v-if="btnList.afterList.length">
            <el-button>
              更多<i
                class="el-icon-arrow-down el-icon--right"
                style="fontsize: 12px"
              ></i>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item
                  v-for="item in btnList.afterList"
                  :key="item.value"
                >
                  <div
                    v-if="item.value === 'add'"
                    style="width: 100%; height: 100%; padding: 0 10px"
                    :plain="true"
                    :disabled="addBtn"
                    @click="addOrg"
                  >
                    新增
                  </div>
                  <div
                    v-if="item.value === 'delDept'"
                    style="width: 100%; height: 100%; padding: 0 10px"
                    :plain="true"
                    :disabled="!canDelete"
                    @click="delDept"
                  >
                    删除
                  </div>
                  <div
                    v-if="item.value === 'orgDeptImport'"
                    style="width: 100%; height: 100%; padding: 0 10px"
                    :plain="true"
                    @click="downloadTemplate('org_dept_import')"
                  >
                    下载部门模板
                  </div>
                  <el-upload
                    v-if="item.value === 'orgDeptInput'"
                    :headers="uploadInfo.headers"
                    :show-file-list="false"
                    :on-error="uploadError"
                    :on-success="uploadSuccess"
                    :before-upload="beforeUpload"
                    :action="uploadInfo.action"
                  >
                    <div style="width: 100%; height: 100%; padding: 0 10px">
                      导入部门
                    </div>
                  </el-upload>
                  <div
                    v-if="item.value === 'orgUserImport'"
                    style="width: 100%; height: 100%; padding: 0 10px"
                    @click="downloadTemplate('org_user_import')"
                  >
                    下载人员模板
                  </div>
                  <el-upload
                    v-if="item.value === 'orgUserInput'"
                    :headers="uploadUserInfo.headers"
                    :show-file-list="false"
                    :on-error="uploadError"
                    :on-success="uploadSuccess"
                    :before-upload="beforeUpload"
                    :action="uploadUserInfo.action"
                  >
                    <div style="width: 100%; height: 100%; padding: 0 10px">
                      {{ item.label }}
                    </div>
                  </el-upload>
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
        <div class="left-container-header border-style-bottom">
          <el-input
            v-model="treeInfo.query.keyword"
            style="flex: 1; margin-right: 10px"
            :clearable="true"
            placeholder="请输入部门名称/编码"
            @keyup.enter.native="init"
          ></el-input>
          <el-button @click="init">搜索</el-button>
        </div>
        <div class="left-container-main main-flex">
          <el-tree
            ref="menuTree"
            :data="treeInfo.data"
            highlight-current
            :props="treeInfo.defaultProps"
            node-key="codeRule"
            :default-expand-all="true"
            :expand-on-click-node="false"
            @node-click="handleNodeClick"
          />
        </div>
      </div>
      <div class="right-container">
        <div v-if="showDeptSubmitBox" class="layui-card-body">
          <!-- 部门 -->
          <div class="layui-btn-container border-style-bottom">
            <el-button :plain="true" :disabled="saveBtn" @click="updateOrg">{{
              $t('btn_save')
            }}</el-button>
          </div>
          <div>
            <page-form
              class="paddingBox order-model-formBox flex_wrap_start_start"
              v-model:ref-obj="formOrgInfo.ref"
              :data="formOrgInfo.data"
              :field-list="formOrgInfo.fieldList"
              :rules="formOrgInfo.rules"
              :label-width="formOrgInfo.labelWidth"
            >
            </page-form>
          </div>
        </div>
        <!-- 用户 -->
        <div v-if="UserBox" class="layui-card-body">
          <div class="opt-header border-style-bottom">
            <page-filter
              v-model:query="filterInfo.query"
              :filter-list="filterInfo.list"
            >
              <template
                v-if="$permission('organization:userAdd')"
                v-slot:filter-Authorization
              >
                <el-button :disabled="currentDeptId <= 0" @click="Authorization"
                  >授权</el-button
                >
              </template>
            </page-filter>
          </div>
          <!-- <table-container
            :refresh="tableInfo.refresh"
            :init-curpage="tableInfo.initCurpage"
            v-model:data="tableInfo.data"
            :api="tableInfo.api"
            :query="filterInfo.query"
            :field-list="tableInfo.fieldList"
            :handle="tableInfo.handle"
            @handleEvent="handleEvent"
          >
            <template v-slot:col-userName="scope">
              <span class="slip-edit" @click="openUserInfoDetails(scope.row)">{{
                scope.row.userName
              }}</span>
            </template>
            <template v-slot:col-electronicSignaturePaths="scope">
              <div
                v-if="
                  scope.row.electronicSignaturePaths &&
                  scope.row.electronicSignaturePaths.length &&
                  scope.row.electronicSignaturePaths[0].filePath
                "
                class="showImage"
                @click="viewImg(scope.row, scope.$index)"
              >
                <el-image
                  class="image"
                  :src="
                    baseUrl +
                    '/pub' +
                    scope.row.electronicSignaturePaths[0].filePath
                  "
                ></el-image>
              </div>
              <tableUploadImg
                v-else
                title="上传签名"
                :index="scope.$index"
                @upDateUpload="upDateUpload"
              />
            </template>
          </table-container> -->
          <!-- S 权限组授权列表 -->
          <CategoryList
            :categoryList="tableInfo.data"
            :showCheck="false"
            :queryParams="cateQueryParams"
            @delete="handleDelete"
          ></CategoryList>
          <!-- E 权限组授权列表 -->
        </div>
      </div>
      <!-- 新增修改弹窗 -->
      <page-dialog
        v-if="userDialogInfo.visible"
        :title="userDialogInfo.title[userDialogInfo.type]"
        v-model:visible="userDialogInfo.visible"
        :width="userDialogInfo.width"
        :bt-loading="userDialogInfo.btLoading"
        :bt-list="userDialogInfo.btList"
      >
        <!-- form -->
        <page-form
          class="paddingBox order-model-formBox flex_wrap_start_start"
          v-model:ref-obj="userFormInfo.ref"
          :data="userFormInfo.data"
          :field-list="userFormInfo.fieldList"
          :rules="userFormInfo.rules"
          :label-width="userFormInfo.labelWidth"
        >
        </page-form>
      </page-dialog>
      <page-dialog
        v-if="userInfoDetails.visible"
        :title="userInfoDetails.title"
        v-model:visible="userInfoDetails.visible"
        :width="userInfoDetails.width"
        :bt-list="userInfoDetails.btList"
      >
        <basic-information :info="infoList"></basic-information>
      </page-dialog>
      <!---新增部门--->
      <page-dialog
        v-if="modifyInfo.visible"
        :title="modifyInfo.title"
        v-model:visible="modifyInfo.visible"
        :width="modifyInfo.width"
        :bt-list="modifyInfo.btList"
      >
        <page-form
          class="paddingBox order-model-formBox flex_wrap_start_start"
          v-model:ref-obj="formOrgInfo.ref"
          :data="formOrgInfo.modifyData"
          :field-list="formOrgInfo.modifyFieldList"
          :rules="formOrgInfo.rules"
          :label-width="formOrgInfo.labelWidth"
        >
        </page-form>
      </page-dialog>
      <select-role
        v-if="selectRoleInfo.visible"
        v-model:show-dialog="selectRoleInfo.visible"
        :default-list="selectRoleInfo.defaultList"
        @callback="addRoleCallback"
      />
      <select-auth
        v-if="selectAuthInfo.visible"
        v-model:show-dialog="selectAuthInfo.visible"
        :query="selectAuthInfo.query"
        :query-tree="selectAuthInfo.queryTree"
        @callback="addAuthCallback"
      />
    </div>
    <EleGallery
      v-if="viewImgInfo.visible"
      v-model:show-dialog="viewImgInfo.visible"
      :file-list="viewImgInfo.list"
      :title="viewImgInfo.title"
      :show-delete="true"
      :multiple-sheets="true"
      @callbackEle="callbackEle"
    />
    <!-- S 授权弹窗 -->
    <CategoryDialog
      v-if="categoryOpen"
      ref="cateDialog"
      :categoryList="categoryList"
      :open="categoryOpen"
      :total="total"
      :queryParams="queryParams"
      @getListDialog="getListDialog"
      @search="categorySearch"
      @submit="submit"
      @close="categoryClose"
      @handleSelectionChange="handleSelectionChange"
      @select="select"
    ></CategoryDialog>
    <!-- E 授权弹窗 -->
  </div>
</template>

<script setup name="organization">
import {
  getCategoryListSelect,
  getCategoryDetail,
  addCategory,
  updateCategory,
  deleteCategoryById,
  filePortfolio,
} from '@/api/fileManager'
import CategoryList from './categoryList.vue'
import CategoryDialog from './categoryDialog.vue'
import { handleTree } from '@/utils/index'
import { resetPassword } from '@/api/pub.js'
import EleGallery from '@/components/NewUpload/eleGallery'
import { mappingUserRole, deleteMappingUserRole } from '@/api/mapping'
import { getDeptClassificationPage } from '@/api/core'
import { createDeptWithPrimaryKey, updateDept, deleteDept } from '@/api/core'
import {
  getOrganizationUserPage,
  createUser,
  updateUser,
  deleteUser,
  batchUpdatePermissions,
  deletePermissionsByEntity,
  updateElectronicSignaturePath,
} from '@/api/base'
import tableUploadImg from '@/components/NewUpload/tableUploadImg'
import { ElLoading } from 'element-plus'
import _ from 'lodash'
import { exportTemplateExcel } from '@/api/pub'

const { proxy } = getCurrentInstance()
const $route = useRoute()

const identify = ref({
  // 启用停用标识 1-启用 0-停用
  start: '1',
  stop: '0',
})
// 编辑文档目录
const formVal = ref({
  status: identify.value.start,
  categoryName: undefined,
  codeRule: undefined,
})
// 分类form对象
const dataForm = ref({
  queryParamsForm: {
    status: identify.value.start,
    categoryName: undefined,
    codeRule: undefined,
  },
})
const listTemp = ref([])
let categoryName = ref('')
let categoryOpen = ref(false)
let isAdd = ref(true) // 是否是新增
let currentCategory = ref({}) // 当前触发文档目录
const categoryList = ref([]) // 授权权限组弹窗列表
const categoryListTemp = ref([]) // 授权权限组弹窗列表缓存
let cateList = ref([]) // 授权权限组列表
let cateListTemp = ref([]) // 授权权限组列表缓存（弹窗取消重置列表数据）
const open = ref(false)
let total = ref(0) // 授权权限组弹窗类别总数
let cateTotal = ref(0) // 文档目录列表总数
const cateOptions = ref(undefined) // 文档目录
// 文档目录弹窗选择数据
let selectCategory = ref([])
const data = reactive({
  form: {},
  queryParams: {
    curPage: 1,
    pageSize: 10,
  },
})
const currentNodeKey = ref('')

const { queryParams, form } = toRefs(data)
const baseUrl = ref(import.meta.env.VITE_APP_BASE_API)
const btnList = ref({
  beforeList: [],
  afterList: [],
})
const hideNum = ref(2)
const uploadInfo = ref({
  action: baseUrl.value + '/core/depts/import/excel',
  headers: {
    Authorization: proxy.$store.state.user.token,
  },
  loading: {},
})
const uploadUserInfo = ref({
  action: baseUrl.value + '/base/users/import/excel',
  headers: {
    Authorization: proxy.$store.state.user.token,
  },
  loading: {},
})
const addBtn = ref(true) //控制左侧树节点上方新增按钮状态
const saveBtn = ref(true)
// 权限树
const treeInfo = ref({
  data: [],
  nodeKey: 'code',
  checked: [],
  defaultProps: { label: 'categoryName', children: 'children' },
  selectNode: {},
  query: {},
})
const formOrgInfo = ref({
  ref: null,
  data: {},
  modifyData: {},
  labelWidth: '120px',
  fieldList: [
    {
      label: '目录名称',
      value: 'categoryName',
      type: 'input',
    },
    {
      label: '目录编码',
      value: 'codeRule',
      type: 'input',
      maxlength: 50,
    },
    {
      label: '状态',
      value: 'status',
      type: 'radio-model',
      code: 'new_enabled_type',
    },
  ],
  modifyFieldList: [
    {
      label: '目录名称',
      value: 'categoryName',
      type: 'input',
    },
    {
      label: '目录编码',
      value: 'codeRule',
      type: 'input',
      maxlength: 50,
    },
    {
      label: '状态',
      value: 'status',
      type: 'radio-model',
      code: 'new_enabled_type',
    },
  ],
  rules: {
    categoryName: [
      { required: true, message: '请输入目录名称', trigger: 'blur' },
    ],
    codeRule: [{ required: true, message: '请输入目录编码', trigger: 'blur' }],
  },
})
// 过滤相关配置
const filterInfo = ref({
  query: {
    sort: 'create_time desc',
    searchType: 'user',
    deptId: '',
    statusMult: '0,1',
    type: 'normal',
    orgId: proxy.$store.state.user.userInfo.user.orgId,
  },
  list: [
    { type: 'slot', value: 'Authorization', label: '授权' },
    { type: 'slot', value: 'btnDelete', label: '删除' },
  ],
})
// 用户弹窗相关
const userDialogInfo = ref({
  title: {
    create: '添加用户',
    update: '修改用户',
  },
  visible: false,
  type: '',
  width: '40%',
  btLoading: false,
  btList: [
    {
      label: '关闭',
      type: '',
      icon: '',
      event: closeUserDialog,
      show: true,
    },
    {
      label: '保存',
      type: 'primary',
      icon: '',
      event: saveUser,
      saveLoading: false,
      show: true,
    },
  ],
})
const userInfoDetails = ref({
  title: '员工信息',
  visible: false,
  width: '40%',
  btList: [
    {
      label: '关闭',
      type: '',
      icon: '',
      event: closeUserInfoDetails,
      show: true,
    },
  ],
})
// 用户表单相关
const userFormInfo = ref({
  ref: null,
  data: {},
  fieldList: [
    {
      label: '工号',
      value: 'userName',
      type: 'input',
      required: true,
      disabled: true,
    },
    { label: '姓名', value: 'name', type: 'input', required: true },
    {
      label: '性别',
      value: 'sex',
      type: 'select-model',
      required: true,
      code: 'sex',
    },
    {
      label: '证件类型',
      value: 'certificateType',
      type: 'select-model',
      code: 'certificate_type',
    },
    {
      label: '证件号码',
      value: 'certificateNum',
      type: 'input',
      validator: proxy.$validate.idCard,
    },
    {
      label: '联系电话',
      value: 'tel',
      type: 'input',
      validator: proxy.$validate.cellphone,
    },
    {
      label: '邮箱',
      value: 'email',
      type: 'input',
      validator: proxy.$validate.mail,
    },
    {
      label: '是否继承部门资源',
      value: 'isInheritance',
      type: 'select-model',
      code: 'yes_or_no',
    },
  ],
  rules: {},
  labelWidth: '150px',
})
const currentDeptId = ref(0)
const addOrUpdate = ref('')
const UserBox = ref(true)
const showDeptSubmitBox = ref(false)
const selectRows = ref([])
const tableData = ref([]) //编辑的用户数据
const isCascade = ref(undefined)
// 表格相关
const tableInfo = ref({
  selections: [],
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: getOrganizationUserPage,
  fieldList: [
    { label: '权限组', value: 'filePortfolioName' },
    { label: '权限组', value: 'filePortfolioName', type: 'slot' },
    { label: '部门', value: 'deptName' },
    { label: '性别', value: 'sexValue' },
    { label: '联系电话', value: 'tel' },
    { label: '角色', value: 'roleNames' },
    { label: '状态', value: 'statusValue' },
    { label: '是否锁定', value: 'lockedValue' },
    { label: '签名', value: 'electronicSignaturePaths', type: 'slot' },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '100',
    btList: [
      { label: '角色', event: addRoles, show: true },
      { label: '权限', event: addAuth, show: true },
      { label: '修改', event: editUser, show: true },
    ],
  },
})
const defaultDepotList = ref([])
const selectRoleInfo = ref({
  visible: false,
  userId: '',
  defaultList: [],
})
const selectAuthInfo = ref({
  visible: false,
  userId: '',
  query: {
    subjectId: '',
    subjectType: 'user',
  },
  queryTree: {},
})

const infoList = ref({
  data: {},
  fieldList: [
    { label: '工号', value: 'userName' },
    { label: '姓名', value: 'name' },
    { label: '性别', value: 'sexValue' },
    { label: '证件类型', value: 'certificateTypeValue' },
    { label: '证件号码', value: 'certificateNum' },
    { label: '联系电话', value: 'tel' },
    { label: '邮箱', value: 'email' },
    { label: '状态', value: 'statusValue' },
  ],
})
const addOrUpdateType = ref('')
const orgRoute = ref({})
const modifyInfo = ref({
  visible: false,
  title: '新增部门',
  width: '60%',
  btLoading: false,
  btList: [
    {
      label: '关闭',
      type: '',
      icon: '',
      event: closeModifyDept,
      show: true,
    },
    {
      label: '保存',
      type: 'primary',
      icon: '',
      event: updateOrg,
      saveLoading: false,
      show: true,
    },
  ],
})
const viewImgInfo = ref({
  visible: false,
  list: [],
  title: '签名',
  row: {},
  index: '',
})

const canDelete = computed(() => {
  return (
    treeInfo.value.selectNode.children &&
    treeInfo.value.selectNode.children.length === 0
  )
})

watch(
  () => treeInfo.value.data,
  () => {
    if (orgRoute.value && orgRoute.value.name === 'organization') {
      return
    }
    UserBox.value = false
    showDeptSubmitBox.value = false
    addBtn.value = true
    saveBtn.value = true
  },
  {
    deep: true,
  }
)

watch(
  () => $route,
  (route) => {
    proxy.$nextTick(() => {
      proxy.$forceUpdate()
    })
    orgRoute.value = route
    const params = route.params
    if (route.name === 'organization') {
      init(params)
    }
  },
  {
    immediate: true,
  }
)
onActivated(() => {
  orgRoute.value = proxy.$route
  const params = proxy.$route.params
  if (proxy.$route.name === 'organization') {
    init(params)
  }
})
onMounted(() => {
  getConfigList()
  initRules()
  _filePortfolio()
  if (orgRoute.value && orgRoute.value.name === 'organization') {
    return
  }
  init()
})
// 查询权限组数据
function categorySearch(val) {
  queryParams.value = Object.assign({ curPage: 1 }, val)
  _filePortfolio()
}
function submit() {
  queryParams.value.curPage = 1
  // 设置已选权限组id，弹窗新加数据使用filePortfolioId，一起已有数据使用id
  selectCategory.value.forEach((element) => {
    element.filePortfolioId = element.filePortfolioId || element.id
  })
  // 授权需要将所有数据合并到列表
  cateList.value = [...new Set(cateList.value.concat(selectCategory.value))]
  cateListTemp.value = proxy.$fn.deepClone(cateList.value)
  selectCategory.value = []
  categoryOpen.value = false
}
function handleSelectionChange(data) {
  selectCategory.value = [...new Set(selectCategory.value.concat(data))]
}
// 移除选中的项
function select(selection, row) {
  let selected = selection.length && selection.indexOf(row) !== -1
  if (!selected) {
    selectCategory.value.forEach((element, index) => {
      if (element.id === row.id) {
        selectCategory.value.splice(index, 1)
      }
    })
  }
}
function categoryClose() {
  queryParams.value.curPage = 1
  selectCategory.value = []
  categoryOpen.value = false
  // cateList.value = proxy.$fn.deepClone(cateListTemp.value)
}
function getListDialog() {
  _filePortfolio()
}
/** 查询授权权限组列表 */
function _filePortfolio() {
  filePortfolio(queryParams.value).then((res) => {
    categoryList.value = res.data
    total.value = res.total
    synchronousList()
  })
}
// 打开弹窗设置选中数据与需要授权数据同步
function synchronousList() {
  delete queryParams.value.searchValue
  categoryList.value.forEach((element, index) => {
    cateList.value.forEach((item) => {
      // 设置禁用并且选中
      if (element.id === item.filePortfolioId) {
        item.isDisable = true
        item.selected = true
        item.id = item.filePortfolioId
        categoryList.value[index] = item
      }
    })

    // 设置分页切换后选中效果
    selectCategory.value.forEach((item) => {
      if (element.id === item.id) {
        item.selected = true
        categoryList.value[index] = item
      }
    })
  })
  // 保证数据可以正常选中
  setTimeout(() => {
    try {
      proxy.$refs.cateDialog.toogleRow()
    } catch (error) {}
  }, 0)
}
function viewImg(row, index) {
  //查看图片
  if (
    row.electronicSignaturePaths &&
    row.electronicSignaturePaths.length &&
    row.electronicSignaturePaths[0].filePath
  ) {
    viewImgInfo.value.row = row
    viewImgInfo.value.index = index
    viewImgInfo.value.visible = true
    viewImgInfo.value.list = [
      {
        name: row.electronicSignaturePaths[0].filePath,
        url: baseUrl.value + '/pub' + row.electronicSignaturePaths[0].filePath,
        uid: new Date().getTime() + (1 + Math.random()),
      },
    ]
  }
}
function callbackEle() {
  let row = proxy.$fn.deepClone(viewImgInfo.value.row)
  row.electronicSignaturePaths = []
  updateElectronicSignaturePath(row).then((res) => {
    if (res && res.success) {
      tableInfo.value.refresh = Math.random()
    }
  })
}
function upDateUpload(res) {
  let params = proxy.$fn.deepClone(tableInfo.value.data[res.index])
  params.electronicSignaturePaths = [
    {
      filePath: res.data[0],
    },
  ]
  updateUser(params).then((res) => {
    if (res && res.success) {
      tableInfo.value.refresh = Math.random()
    }
  })
}
// 获取列表
function getConfigList() {
  let arr = [
    {
      label: '新增',
      value: 'add',
      show: proxy.$permission('organization:add'),
    },
    {
      label: '删除',
      value: 'delDept',
      show: proxy.$permission('organization:del'),
    },
    {
      label: '下载部门模板',
      value: 'orgDeptImport',
      show: proxy.$permission('organization:downloadDeptTemplate'),
    },
    {
      label: '导入部门',
      value: 'orgDeptInput',
      show: proxy.$permission('organization:deptImport'),
    },
    {
      label: '下载人员模板',
      value: 'orgUserImport',
      show: proxy.$permission('organization:downloadUserTemplate'),
    },
    {
      label: '导入人员',
      value: 'orgUserInput',
      show: proxy.$permission('organization:userImport'),
    },
  ]
  let list = arr.filter((item) => item.show)
  if (list.length > 0) {
    btnList.value.beforeList = list.slice(0, 2)
    btnList.value.afterList = list.slice(2, list.length)
  }
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    // 对表格获取到的数据做处理
    case 'tableCheck':
      tableInfo.value.selections = data
      break
  }
}
// 加载组织架构
function init(params) {
  console.info(params)
  getCategoryListSelect({
    includeStop: true,
  }).then((response) => {
    let res = handleTree(response.data, 'id')
    treeInfo.value.data = res
  })
  /*   getDeptTrees(treeInfo.value.query).then((res) => {
    if (res.success) {
      debugger
      treeInfo.value.data = res.data
      if (treeInfo.value.query.keyword) {
        showDeptSubmitBox.value = false
        UserBox.value = false
      }
      if (params && params.deptId) {
        getTreeItem(res.data, params)
      } else if (params && params.id) {
        getTreeItem(res.data, params)
      }
    }
  }) */
}
function getTreeItem(data, param) {
  data.forEach((item) => {
    if (item.children && item.children.length) {
      getTreeItem(item.children, param)
    }
    if (item.id.toString() === param.deptId) {
      handleNodeClick(item)
      return
    } else if (item.id === param.id) {
      handleNodeClick(item)
      proxy.$nextTick(function () {
        proxy.$refs.menuTree.setCurrentKey(item.id)
      })
      return
    }
  })
}
// 初始化校验规则
function initRules() {
  //const formOrgInfo = formOrgInfo.value;
  // formOrgInfo.rules = proxy.$initRules(formOrgInfo.fieldList);
}
//添加部门
function addOrg() {
  addOrUpdate.value = createDeptWithPrimaryKey
  addOrUpdateType.value = 'createDeptWithPrimaryKey'
  formOrgInfo.value.modifyData = {}
  let parent = proxy.$refs.menuTree.getCurrentNode()
  formOrgInfo.value.modifyData = {
    pid: parent.id,
    status: '1',
  }
  modifyInfo.value.visible = true
}
function closeModifyDept() {
  modifyInfo.value.visible = false
}
//删除部门
function delDept() {
  const ids = [currentDeptId.value]
  proxy.$handleAPI('delete', deleteDept, ids).then((resp) => {
    if (resp && resp.success) {
      formOrgInfo.value.data = {}
      userFormInfo.value.data = {}
      tableInfo.value.data = []
      tableInfo.value.selections = []
      init()
    }
  })
}
// 获取部门信息和部门内人员列表
function getOrgDetail(node) {
  getCategoryDetail(node.id).then((res) => {
    formOrgInfo.value.data = {
      ...res.data,
    }
    tableInfo.value.data = res.data.details

    cateList.value = res.data.details
    cateListTemp.value = proxy.$fn.deepClone(res.data.details)
    listTemp.value = proxy.$fn.deepClone(res.data.details)
    cateTotal.value = res.total
    dataForm.value.queryParamsForm.categoryName = res.data.categoryName
    dataForm.value.queryParamsForm.codeRule = res.data.codeRule
    dataForm.value.queryParamsForm.status = res.data.status
    formVal.value = proxy.$fn.deepClone(dataForm.value.queryParamsForm)
  })
}
function handleDelete(scope) {
  const index = scope.$index
  tableInfo.value.data.splice(index, 1)
}
// 关闭用户弹窗
function closeUserDialog() {
  userDialogInfo.value.visible = false
}
function closeUserInfoDetails() {
  userInfoDetails.value.visible = false
}
function openUserInfoDetails(row) {
  infoList.value.data = row
  userInfoDetails.value.visible = true
}
// 加载当前部门下用户列表
function loadUserList(id) {
  proxy.$nextTick(function () {
    tableInfo.value.refresh = Math.random()
  })
}
// 点击树节点
function handleNodeClick(node) {
  // formOrgInfo.value.ref.resetFields();
  addBtn.value = false
  addOrUpdate.value = updateDept
  addOrUpdateType.value = 'updateDept'
  treeInfo.value.selectNode = node
  currentDeptId.value = node.id
  if (node.id !== -1) {
    saveBtn.value = false
    // 获取部门信息和部门内人员列表
    isAdd.value = false
    formVal.value = proxy.$fn.deepClone(node)
    dataForm.value.queryParamsForm = node
    currentCategory.value = node
    getOrgDetail(node)
    UserBox.value = true
    showDeptSubmitBox.value = true
    //loadUserList(node.id)
  } else {
    formOrgInfo.value.data = {}
    showDeptSubmitBox.value = false
    saveBtn.value = true
    UserBox.value = true
    //loadUserList()
  }
}
/** 新增按钮操作 */
function Authorization() {
  categoryOpen.value = true
  queryParams.value.curPage = 1
  queryParams.value.pageSize = 10
}
// 新增用户或编辑
function Authorization1() {
  if (canNotAddUser.value) {
    proxy.$alert(`该部门已停用，无法添加人员`, '操作提示', {
      confirmButtonText: '确定',
    })
    return
  }
  const _userFormInfo = userFormInfo.value
  _userFormInfo.rules = proxy.$initRules(_userFormInfo.fieldList)
  _userFormInfo.data = {}
  userDialogInfo.value.type = 'create'
  userDialogInfo.value.visible = true
  _userFormInfo.data.type = 'normal'
  _userFormInfo.data.deptId = formOrgInfo.value.data.id
  _userFormInfo.fieldList[8].show = false
  _userFormInfo.fieldList[9].show = false
  _userFormInfo.fieldList[10].show = false
  _userFormInfo.fieldList[11].show = true
  _userFormInfo.fieldList[0].disabled = false
}
function editUser(data) {
  userFormInfo.value.data = {}
  ;(userFormInfo.value.data = JSON.parse(JSON.stringify(data))()),
    (userFormInfo.value.rules = proxy.$initRules(userFormInfo.value.fieldList))
  userDialogInfo.value.visible = true
  userDialogInfo.value.type = 'update'
  userFormInfo.value.fieldList[8].show = true
  userFormInfo.value.fieldList[9].show = true
  userFormInfo.value.fieldList[10].show = true
  userFormInfo.value.fieldList[11].show = false
  userFormInfo.value.fieldList[0].disabled = true
}
function saveUser() {
  userFormInfo.value.ref.validate((valid) => {
    if (valid) {
      let api
      const params = userFormInfo.value.data
      const type = userDialogInfo.value.type
      if (type === 'create') {
        api = createUser
      } else if (type === 'update') {
        api = updateUser
      } else {
        return
      }
      api(params).then((res) => {
        if (res.success) {
          userDialogInfo.value.visible = false
          tableInfo.value.refresh = Math.random()
          userFormInfo.value.data = {}
        }
      })
    }
  })
}
function search() {
  const _tableInfo = tableInfo.value
  _tableInfo.initCurpage = Math.random()
  _tableInfo.refresh = Math.random()
}
function addRoles(row) {
  selectRoleInfo.value.defaultList = row.roleIds
  selectRoleInfo.value.visible = true
  selectRoleInfo.value.userId = row.id
}
function addRoleCallback(rows = []) {
  const data = []
  if (rows.length > 0) {
    rows.forEach((item) => {
      data.push({
        userId: selectRoleInfo.value.userId,
        roleId: item.id,
      })
    })
    mappingUserRole(data).then((resp) => {
      if (resp && resp.success) {
        loadUserList(currentDeptId.value)
      }
    })
  } else {
    //为空的时候 删除该角色已有资源
    let entity = { userId: selectRoleInfo.value.userId }
    deleteMappingUserRole(entity).then((resp) => {
      if (resp && resp.success) {
        loadUserList(currentDeptId.value)
      }
    })
  }
}
// 用户多选
function listSelect(rows) {
  selectRows.value = []
  for (let item of rows) {
    selectRows.value.push(item.id)
  }
}
// 更新或添加部门
function updateOrg() {
  let _formOrgInfo = formOrgInfo.value
  formOrgInfo.value.ref.validate((valid) => {
    if (valid) {
      let params = {}
      if (addOrUpdateType.value === 'createDeptWithPrimaryKey') {
        params = _formOrgInfo.modifyData
      } else {
        params = _formOrgInfo.data
      }
      addOrUpdate.value(params).then((res) => {
        if (res.success) {
          let param = {}
          //新增部门时 需要insert成功后的部门id  将id传给部门资源的新增方法中使用
          if (addOrUpdate.value.name == 'createDeptWithPrimaryKey') {
            param.id = res.data
          } else {
            param.id = formOrgInfo.value.data.id
          }
          closeModifyDept()
          // updateResource(isCascade.value)
          init(param)

          proxy.$message({
            message: `操作成功`,
            type: 'success',
            duration: 1500,
            showClose: true,
          })
        }
      })
    }
  })
}
function addAuth(row) {
  // selectAuthInfo.value.queryTree.userId = row.id;
  selectAuthInfo.value.query.subjectId = row.id
  selectAuthInfo.value.query.disableRole = row.id
  selectAuthInfo.value.queryTree.disableRole = row.id
  selectAuthInfo.value.queryTree.orgId =
    proxy.$store.state.user.userInfo.user.orgId
  selectAuthInfo.value.visible = true
  selectAuthInfo.value.userId = row.id
}
function addAuthCallback(authList = []) {
  if (authList.length) {
    const data = []
    authList.forEach((authNode) => {
      data.push({
        subjectId: selectAuthInfo.value.userId,
        subjectType: 'user',
        resourceType: authNode.type,
        resourceId: authNode.id,
        level: 'own_and_allot',
      })
    })
    batchUpdatePermissions(data).then((res) => {
      if (res && res.success) {
        dialogInfo.value.visible = false
      }
    })
  } else {
    const data = {
      subjectType: 'user',
      subjectId: selectAuthInfo.value.userId,
    }
    deletePermissionsByEntity(data)
  }
}

function beforeUpload() {
  //发生请求时打开加载动画
  uploadInfo.value.loading = ElLoading.service({
    fullscreen: true,
    background: 'rgba(255,255,255,.4)',
  })
  return true
}
function uploadSuccess(resp) {
  uploadInfo.value.loading.close()
  if (resp && resp.success) {
    proxy.$message.success({
      duration: 3000,
      showClose: true,
      message: resp.msg,
    })
    init()
  } else {
    proxy.$message.error({
      message: resp.msg,
      duration: 3000,
      showClose: true,
    })
  }
}
function uploadError(err) {
  if (err) {
    proxy.$message.error({
      message: '系统错误',
      duration: 3000,
      showClose: true,
    })
  }
  uploadInfo.value.loading.close()
}
function downloadTemplate(tag) {
  exportTemplateExcel(tag).then((res) => {
    if (res) {
      proxy.$fn.parseExcel(res)
    }
  })
}
</script>

<style lang="scss" scoped>
.app-container {
  height: calc(100vh - 83px);
}
.left-container {
  min-width: 320px;
  .left-container-header {
    display: flex;
    align-items: center;
    //justify-content: space-around;
  }
}
.main-flex {
  flex-grow: 1;
  display: flex;
  flex-wrap: nowrap;
  height: calc(100% - 240px);
  .el-tree {
    width: 100%;
    padding: 0 20px 20px;
    overflow-y: auto;
    :deep(.el-tree-node__children) {
      overflow: initial;
    }
  }
}
.img-wraper {
  width: 100px;
  height: 50px;
  img {
    max-width: 100%;
    max-height: 100%;
  }
}
.showImage {
  width: 100%;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  .image {
    max-width: 40px !important;
    max-height: 40px !important;
  }
}
:deep(.full) {
  width: 100% !important;
}
</style>
